<template>
  <Tabs v-model:activeKey="state.activeKey" tabPosition="bottom">
    <!--      表格-->
    <TabPane key="1" :forceRender="true">
      <SuperTable ref="superTableRef" search pager border align="center" :columns="columns" :data-request="fetchData" :export-config="{}" header-title="设备使用记录" />
    </TabPane>

    <!--      定位-->
    <TabPane key="2" :forceRender="true">
      <div class="positioning-title">
        <h2>样本定位</h2>
        <Button type="primary" @click="changeTabFn('1')">返回</Button>
      </div>
      <Card>
        <div style="display: flex; align-items: center; height: 600px; padding: 0 20px">
          <StorageLocation :row="state.boxData?.rows" :cols="state.boxData?.cols" :list="state.boxList" />
          <div style="flex: 1; margin-left: 30px">
            <vxe-table height="600px" align="center" :data="state.boxList">
              <vxe-column type="seq" title="序号" />
              <vxe-column field="specimen" :title="$t('specimen.name')" :formatter="({ cellValue }) => cellValue?.name" />
              <vxe-column field="specimen" :title="$t('specimen.original_serial')" :formatter="({ cellValue }) => cellValue?.originalSerial" />
              <vxe-column field="serial" :title="`${$t('specimen.sample')}序列号`" />
              <vxe-column field="epc" :title="$t('specimen.epc')" />
              <vxe-column field="capacity" title="容量(ml)" />
              <vxe-column field="position" title="绑定位置" />
              <vxe-column field="$action" title="操作">
                <template #default="{ row }">
                  <Button type="link" @click="viewButtonClickFn(row)">查看</Button>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </div>
      </Card>
      <SampleSeeModal v-model:show-modal="state.showSampleSeeModal" :id="state.modalData?.specimenId" :data="state.modalData" />
    </TabPane>
  </Tabs>

  <!--   打印   -->
  <DraggableModal v-model:visible="state.showPrintModal" title="打印页详情" width="900px" @cancel="printEndFn">
    <template #footer>
      <Button @click="printEndFn">关闭</Button>
    </template>

    <div style="font-size: 16px; margin: 0 50px 15px; display: flex; justify-content: space-between">
      <span style="white-space: nowrap">打印批号: {{ state.printData?.printBatchNos }}</span>
      <span style="white-space: nowrap">操作人：{{ state.printData?.userName }}</span>
      <span style="white-space: nowrap">打印时间: {{ state.printData?.createTime }}</span>
    </div>
    <vxe-table align="center" :data="state.printData?.printRecordItems">
      <vxe-column type="seq" title="序号" />
      <vxe-column field="serial" title="序列号" />
      <vxe-column field="epc" :title="$t('specimen.epc')" />
      <vxe-column field="type" title="标签类型" :formatter="({ cellValue }) => useTypeList.find((item) => item.id === cellValue)?.name ?? '未知'" />
    </vxe-table>
  </DraggableModal>

  <!--   入库   -->
  <ViewDrawerIn v-model:showDrawer="state.showInDrawer" :id="state.curId" />

  <!--   出库   -->
  <ViewDrawerOut v-model:show-drawer="state.showOutDrawer" :id="state.curId" />

  <!--   盘点   -->
  <ViewDrawer v-model:show-drawer="state.showCountDrawer" :data="{ id: state.curId }" />

  <!--   移库   -->
  <ViewDrawerMove v-model:show-drawer="state.showMoveDrawer" :id="state.curId" />
</template>

<script setup lang="ts">
import ViewDrawerIn from '@/modules/underlying-data/pages/device-usage-records/components/view-drawer-in/view-drawer-in.vue';
import SuperTable from '@/framework/components/core/super-table/super-table.vue';
import { VxeGridPropTypes } from 'vxe-table';
import type { TableColumnItem } from './columns';
import { baseColumns, devicetypeList, useTypeList } from './columns';
import { reactive, ref } from 'vue';
import { message, Row, Col, Tabs, TabPane, Card } from 'ant-design-vue';
import { getUsageRecordManageData } from '@/api/base/usageRecord-manage-data';
import { DraggableModal } from '@/framework/components/core/draggable-modal';
import Button from '@/framework/components/basic/button/button.vue';
import { getBoxInfo, getLabelPrinting } from '@/modules/sample-inventory/api/device-usage-records';
import StorageLocation from '@/components/StorageLocation.vue';
import SampleSeeModal from '@/components/sample-see-modal/sample-see-modal.vue';
import ViewDrawerOut from '@/modules/underlying-data/pages/device-usage-records/components/view-drawer-out/view-drawer-out.vue';
import ViewDrawer from '@/modules/sample-inventory/pages/inventory-records/components/view-drawer/view-drawer.vue';
import ViewDrawerMove from '@/modules/underlying-data/pages/device-usage-records/components/view-drawer-move/view-drawer-move.vue';

/**
 * data
 */
type State = {
  showPrintModal: boolean;
  showViewModal: boolean;
  showSampleSeeModal: boolean;
  showOutDrawer: boolean;
  showInDrawer: boolean;
  showCountDrawer: boolean;
  showMoveDrawer: boolean;

  curId: any;
  modalData: any;
  printData: any;
  activeKey: '1' | '2';
  boxData: any;
  boxList: any[];
};
const state: State = reactive({
  showPrintModal: false,
  showViewModal: false,
  showSampleSeeModal: false,
  showOutDrawer: false,
  showInDrawer: false,
  showCountDrawer: false,
  showMoveDrawer: false,

  curId: undefined,
  modalData: {},
  printData: {},
  activeKey: '1',
  boxData: {},
  boxList: [],
}) as State;

/**
 * table
 */
const superTableRef = ref<InstanceType<typeof SuperTable>>();
const columns: TableColumnItem[] = [
  ...baseColumns,
  {
    title: '操作',
    field: '$action',
    hideInSearch: true,
    align: 'center',
    fixed: 'right',
    width: 100,
    actions: ({ row }) => [
      {
        label: '查看',
        onClick: async () => {
          switch (row.useType) {
            case 2:
              // 入库
              state.curId = row.parentId;
              state.showInDrawer = true;
              break;
            case 3:
              // 出库
              state.curId = row.parentId;
              state.showOutDrawer = true;
              break;
            case 4:
              // 核销
              break;
            case 5:
              // 盘点
              state.curId = row.parentId;
              state.showCountDrawer = true;
              break;
            case 7:
              // 盒信息
              await boxStartFn(row);
              changeTabFn('2');
              break;
            case 8:
            case 9:
            case 10:
              // 打印
              await printStartFn(row);
              break;
            case 11:
              // 移库
              state.curId = row.parentId;
              state.showMoveDrawer = true;
              break;
          }
        },
      },
    ],
  },
];
const fetchData = async (ori: VxeGridPropTypes.ProxyAjaxQueryParams) => {
  let data = superTableRef.value?.getFormModel();
  let params = {
    pageSize: ori.page.pageSize,
    pageNum: ori.page.currentPage,
    orderBy: [
      {
        field: 'createTime',
        order: 'desc',
      },
    ],
    ...data,
  };
  data.createTimeBtw ? (params.createTimeBtw = data.createTimeBtw.join() + ' 23:59:59') : delete params.createTimeBtw;
  let res = await getUsageRecordManageData(params);
  return res.result;
  // return {
  //   data: [{}, {}, {}],
  //   pageIndex: 1,
  //   pageSize: 10,
  //   total: 100,
  // };
};
const refreshTableFn = () => {
  superTableRef.value?.refreshTable();
};
/**
 * fn
 */
const changeTabFn = (key) => {
  state.activeKey = key;
};
/**
 * 打印
 */
const printStartFn = async (row: any) => {
  const res = await getLabelPrinting(row.id);
  state.printData = res.result;
  state.showPrintModal = true;
};
const printEndFn = () => {
  state.showPrintModal = false;
  state.printData = {};
};
/**
 * 定位
 */
const boxStartFn = async (row: any) => {
  const res = await getBoxInfo({ boxTypeEpc: row.boxEpc });
  state.boxData = res.result;
  const sub = await getLabelPrinting(row.id);
  state.boxList = handlePosition(sub.result?.locateRecordItems);
};
const handlePosition = (arr) => {
  for (let i = 0; i < arr.length; i++) {
    const cols = state.boxData.cols;
    arr[i].sortIndex = arr[i]?.strainIndex;
    let newPosition;
    if (arr[i].strainIndex < cols) {
      newPosition = 1 + '-' + (arr[i].strainIndex + 1);
    } else if (arr[i].strainIndex >= cols) {
      let row;
      if (arr[i].strainIndex % cols === 0) {
        row = arr[i].strainIndex / cols + 1;
      } else {
        row = Math.ceil(arr[i].strainIndex / cols);
      }
      let col;
      col = (arr[i].strainIndex % cols) + 1;
      newPosition = row + '-' + col;
    }
    arr[i].position = newPosition;
  }
  return arr;
};
const viewButtonClickFn = (row: any) => {
  state.showSampleSeeModal = true;
  state.modalData = row;
};
</script>

<style scoped lang="less">
.positioning-title {
  display: flex;
  justify-content: space-between;
  padding: 30px 20px 30px 40px;
  margin-bottom: 15px;
  font-size: 20px;
  font-weight: 700;
  background-color: #fff;
}
</style>
